package com.itheima.framework;

import com.itheima.framework.view.ViewAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @program: Implementing springmvc
 * @description:
 * @author: zhanghz001
 * @create: 2020-12-05 10:07
 **/
public class DispatcherServlet extends BaseInit {
    //适配器对象
    private static ViewAdapter viewAdapter = new ViewAdapter();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uri = req.getRequestURI();

        Object result = invoke(uri);
        if (result != null) {
            viewAdapter.render(req, resp, result);
        }

    }

    private Object invoke(String uri) {
        //获取执行的方法
        Method method = beanFactory.getMethod(uri);
        if (method != null) {

            //执行方法
            try {
                //获取对象
                //获取执行 结果
                return method.invoke(beanFactory.getUrlBean(uri), null);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
        }
        return null;

    }
}
